<template>
  <div class="payment-container">
    <div class="payment-header">
      <div class="logo">
        <img src="@/assets/tmalllogo.png" alt="Tmall Logo">
      </div>
      <div class="payment-title">
        <h1>订单支付</h1>
      </div>
    </div>

    <div class="payment-content">
      <div class="order-info-box">
        <div class="order-info-header">
          <div class="order-num">订单号：{{ orderId }}</div>
          <div class="order-amount">支付金额：<span class="amount">¥{{ calculatedTotal }}</span></div>
        </div>
        <div v-if="orderProducts.length > 0" class="debug-info">
          <small>(计算总额: ¥{{ calculatedTotal }})</small>
        </div>
        <div class="order-products">
          <div class="product-list-title">商品信息</div>
          <el-scrollbar height="120px">
            <div v-for="(product, index) in orderProducts" :key="index" class="product-item">
              <div class="product-image">
                <img :src="product.mainImg" :alt="product.name">
              </div>
              <div class="product-info">
                <div class="product-name">{{ product.name }}</div>
                <div class="product-price">¥{{ formatPrice(product.price) }} × {{ product.number }}</div>
              </div>
            </div>
          </el-scrollbar>
        </div>
        <div class="countdown">
          <div class="countdown-title">请在以下时间内完成支付：</div>
          <div class="countdown-time">{{ formatTime(countdown) }}</div>
        </div>
      </div>

      <div class="payment-methods">
        <div class="payment-methods-header">
          <h2>选择支付方式</h2>
        </div>
        
        <div class="payment-options">
          <div 
            v-for="(method, index) in paymentMethods" 
            :key="index" 
            class="payment-option"
            :class="{ active: selectedMethod === method.id }"
            @click="selectPaymentMethod(method.id)"
          >
            <div class="payment-icon">
              <img :src="method.icon" :alt="method.name">
            </div>
            <div class="payment-name">{{ method.name }}</div>
          </div>
        </div>

        <div class="qr-code-box">
          <div class="qr-code-title">
            <span>请使用{{ getSelectedMethodName() }}扫描二维码支付</span>
          </div>
          <div class="qr-code">
            <img v-if="selectedMethod === 'alipay'" src="@/assets/paylogo2.png" alt="Alipay QR Code">
            <img v-else src="@/assets/paylogo.png" alt="Other Payment QR Code">
          </div>
          <div class="payment-actions">
            <el-button type="primary" class="pay-button" @click="handlePayment">
              立即支付
            </el-button>
            <el-button type="default" class="cancel-button" @click="cancelPayment">
              取消支付
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import request from '@/utils/http.js';
import paylogo from '@/assets/paylogo.png';
import paylogo2 from '@/assets/paylogo2.png';

const route = useRoute();
const router = useRouter();
const orderId = ref(route.params.orderId || 'TM' + Date.now().toString().slice(-8));
const orderAmount = ref('0.00');
const countdown = ref(900); // 15分钟倒计时
const countdownTimer = ref(null);
const orderProducts = ref([]);
const loading = ref(false);

// 计算订单总额（用于验证）
const calculatedTotal = computed(() => {
  let total = 0;
  orderProducts.value.forEach(product => {
    const price = parseFloat(typeof product.price === 'object' ? product.price.toString() : product.price);
    const quantity = product.number || 0;
    total += price * quantity;
  });
  return total.toFixed(2);
});

// 支付方式
const paymentMethods = ref([
  {
    id: 'alipay',
    name: '支付宝',
    icon: 'https://img.alicdn.com/imgextra/i4/O1CN01XCiY1B1px2zSZZXtd_!!6000000005426-2-tps-108-36.png'
  },
  {
    id: 'wechat',
    name: '微信支付',
    icon: 'https://img.alicdn.com/imgextra/i2/O1CN01Mk916Y1obH3i2NUpW_!!6000000005243-2-tps-108-36.png'
  },
  {
    id: 'bank',
    name: '银联支付',
    icon: 'https://img.alicdn.com/imgextra/i2/O1CN01D0WET11Zh5n75YA8Y_!!6000000003228-2-tps-108-36.png'
  }
]);

const selectedMethod = ref('alipay');

// 获取QR码图片
const qrCodeImage = computed(() => {
  return selectedMethod.value === 'alipay' ? paylogo2 : paylogo;
});

// 获取选中支付方式的名称
const getSelectedMethodName = () => {
  const method = paymentMethods.value.find(m => m.id === selectedMethod.value);
  return method ? method.name : '选择的支付方式';
};

// 选择支付方式
const selectPaymentMethod = (methodId) => {
  selectedMethod.value = methodId;
};

// 格式化倒计时时间
const formatTime = (seconds) => {
  const minutes = Math.floor(seconds / 60);
  const secs = seconds % 60;
  return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
};

// 开始倒计时
const startCountdown = () => {
  countdownTimer.value = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--;
    } else {
      clearInterval(countdownTimer.value);
      ElMessageBox.alert('支付超时，请重新下单', '提示', {
        confirmButtonText: '确定',
        callback: () => {
          router.push('/productOrder');
        }
      });
    }
  }, 1000);
};

// 处理支付
const handlePayment = () => {
  loading.value = true;
  
  setTimeout(() => {
    loading.value = false;
    
    // 显示支付成功消息
    ElMessage({
      type: 'success',
      message: '支付成功！'
    });
    
    // 更新订单状态为已支付
    request.post(`/api/productOrder/pay/${orderId.value}`).then(res => {
      if (res.code === 1) {
        // 跳转到订单列表页
        router.push('/productOrder');
      } else {
        ElMessage.error(res.msg || '支付状态更新失败');
      }
    }).catch(error => {
      console.error('支付异常:', error);
      router.push('/productOrder');
    });
  }, 1500);
};

// 取消支付
const cancelPayment = () => {
  ElMessageBox.confirm('确定要取消支付吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    router.push('/productOrder');
  }).catch(() => {
    // 用户取消操作
  });
};

// 获取订单信息
const getOrderInfo = () => {
  loading.value = true;
  
  request.get(`/api/productOrder/detail/${orderId.value}`).then(res => {
    if (res.code === 1) {
      const orderData = res.data;
      console.log('订单数据:', orderData); // 添加调试信息
      
      // 设置订单金额 - 确保格式正确
      if (orderData.sum) {
        // 转换为数字并格式化为两位小数
        console.log('原始金额:', orderData.sum); // 添加调试信息
        orderAmount.value = parseFloat(orderData.sum).toFixed(2);
        console.log('格式化后金额:', orderAmount.value); // 添加调试信息
      } else {
        orderAmount.value = '0.00';
      }
      
      // 设置商品列表
      orderProducts.value = orderData.productRts || [];
      
      loading.value = false;
    } else {
      ElMessage.error(res.msg || '获取订单信息失败');
      loading.value = false;
    }
  }).catch(error => {
    console.error('获取订单详情失败:', error);
    ElMessage.error('获取订单详情失败');
    loading.value = false;
  });
};

// 格式化价格
const formatPrice = (price) => {
  if (!price) return '0.00';
  return typeof price === 'object' && price.toFixed ? 
    price.toFixed(2) : 
    parseFloat(price).toFixed(2);
};

// 生命周期钩子
onMounted(() => {
  getOrderInfo();
  startCountdown();
});

onUnmounted(() => {
  if (countdownTimer.value) {
    clearInterval(countdownTimer.value);
  }
});
</script>

<style scoped>
.payment-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f7f7f7;
  min-height: 100vh;
}

.payment-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e8e8e8;
}

.logo img {
  height: 40px;
  margin-right: 20px;
}

.payment-title h1 {
  font-size: 24px;
  color: #333;
  margin: 0;
}

.payment-content {
  display: flex;
  gap: 20px;
}

.order-info-box {
  flex: 1;
  width: 500px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.order-info-header {
  display: flex;
  justify-content: space-between;
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 15px;
  margin-bottom: 15px;
}

.order-num {
  color: #666;
  font-size: 14px;
}

.order-amount {
  font-size: 14px;
  color: #666;
}

.amount {
  font-size: 20px;
  color: #ff0036;
  font-weight: bold;
}

.order-products {
  margin-bottom: 20px;
}

.product-list-title {
  font-size: 16px;
  color: #333;
  margin-bottom: 10px;
  font-weight: bold;
}

.product-item {
  display: flex;
  padding: 10px 0;
  border-bottom: 1px dashed #f0f0f0;
}

.product-image {
  width: 60px;
  height: 60px;
  margin-right: 10px;
  flex-shrink: 0;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

.product-info {
  flex: 1;
}

.product-name {
  font-size: 14px;
  color: #333;
  margin-bottom: 5px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.product-price {
  font-size: 12px;
  color: #999;
}

.countdown {
  margin-top: 20px;
  padding-top: 15px;
  border-top: 1px solid #f0f0f0;
}

.countdown-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 5px;
}

.countdown-time {
  font-size: 20px;
  color: #ff0036;
  font-weight: bold;
}

.payment-methods {
  flex: 1;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.payment-methods-header {
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 15px;
  margin-bottom: 20px;
}

.payment-methods-header h2 {
  font-size: 18px;
  color: #333;
  margin: 0;
}

.payment-options {
  display: flex;
  gap: 15px;
  margin-bottom: 30px;
}

.payment-option {
  border: 1px solid #e8e8e8;
  padding: 15px;
  border-radius: 8px;
  cursor: pointer;
  display: flex;
  align-items: center;
  transition: all 0.3s;
}

.payment-option:hover {
  border-color: #ff0036;
}

.payment-option.active {
  border-color: #ff0036;
  background-color: #fff1f1;
}

.payment-icon {
  margin-right: 10px;
}

.payment-icon img {
  height: 24px;
}

.payment-name {
  font-size: 14px;
  color: #333;
}

.qr-code-box {
  text-align: center;
  padding: 30px 0;
}

.qr-code-title {
  margin-bottom: 20px;
  font-size: 16px;
  color: #333;
}

.qr-code {
  width: 200px;
  height: 200px;
  margin: 0 auto 30px;
  padding: 10px;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
}

.qr-code img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.payment-actions {
  display: flex;
  justify-content: center;
  gap: 15px;
}

.pay-button {
  background-color: #ff0036;
  border-color: #ff0036;
  width: 160px;
  height: 40px;
}

.pay-button:hover {
  background-color: #ff3366;
  border-color: #ff3366;
}

.cancel-button {
  width: 160px;
  height: 40px;
}

.debug-info {
  text-align: right;
  color: #999;
  margin-bottom: 10px;
  margin-top: -10px;
}
</style> 